<?php


namespace App\Services;

use App\Models\AdminUser;
use App\Tools\RedisTools;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class EasyWechatEven
{

    public $app;

    public function __construct()
    {
        //配置属性
        $config = config('easyWechat.mode');
        $this->app = Factory::officialAccount($config);
    }
    /**
     * @Notes:判断事件
     * @Author:Planb,
     * @Date: 2022/11/28,
     * @Time: 14:45,
     */
    public  function even($even)
    {
        //关注类型
        if ($even['Event'] == 'subscribe') {
            return '欢迎关注';
        }
        //扫码类型
        if (isset($even['EventKey']) && !empty($even['EventKey'])) {
            $openId = $even['FromUserName'];
            $userInfo = AdminUser::where('wx_open_id',$openId)->first();
            if (!$userInfo) {
                return '请先授权认证';
            }else{
                //登陆成功通知前端跳转页面
                GatewayWorkerService::gatewayWorkerSend(200,'send_message',['open_id'=>$openId,'eventKey'=>$even['EventKey']]);
                //登陆成功返回模板消息
                $this->app->template_message->send([
                    'touser' => $openId,
                    'template_id' => config('easyWechat.template_id'),
                    'url' => 'http://www.cyjyyds.cn/api/link_detail',
                    'data' => [
                        'thing1' => '登录成功',
                        'thing2' => $userInfo['username'],
                        'time' => date('Y-m-d H:i:s'),
                    ],
                ]);

            }
        }
    }

    /**
     * @Notes:绑定open_id
     * @Author:Planb,
     * @Date: 2022/11/29,
     * @Time: 14:22,
     */
    public static function bindOpenId($username, $password, $openId)
    {
        $userInfo = AdminUser::where('username', $username)->where('wx_open_id',$openId)->first();
        if ($userInfo) {
            return StatusNumber::REPEATBIND;
        } else {
           $authResult = Auth::attempt(['username'=>$username,'password'=>$password]);
           //如果有此用户进行绑定
           if ($authResult){
               $bindResult = AdminUser::where('username', $username)->update([
                  'wx_open_id'=>$openId
               ]);
               if ($bindResult){
                   $redis = (RedisTools::getInstance())->connectRedis();
                   $redis->hSet('adminInfo',$openId,base64_encode($password));
                   return StatusNumber::BINDSUCCESS;
               }else{
                   return StatusNumber::BINDFAIL;
               }
           }else{
               //用户名密码错误
               return StatusNumber::USERNAMEORPASSWORDERROR;
           }
        }
    }
}
